package com.demo.log;

import com.demo.common.ResultData;
import org.apache.commons.lang3.StringUtils;

/**
 * @author wangfengchen
 */
public final class LogHelper {

  private static ThreadLocal<LogHelper> local = ThreadLocal.withInitial(LogHelper::new);

  private String ip;

  private String url;


  public static String format(int code, String message, KeyValue... kvs) {
    StringBuilder buf = new StringBuilder(200);
    if (code != 0) {
      buf.append("code = ").append(code).append('\t');
    }
    if (StringUtils.isNotBlank(message)) {
      buf.append("msg：").append(message).append('\t');
    }
    if (kvs != null) {
      for (KeyValue kv : kvs) {
        buf.append(kv.getKey()).append(" = ").append(kv.getValue()).append('\t');
      }
    }
    LogHelper log = local.get();
    if (StringUtils.isNotBlank(log.getIp())) {
      buf.append("ip = ").append(log.getIp()).append('\t');
    }
    if (StringUtils.isNotBlank(log.getIp())) {
      buf.append("url = ").append(log.getUrl()).append('\t');
    }
    int len = buf.length();
    if (len > 0) {
      char ch = buf.charAt(len - 1);
      if (ch == ' ' || ch == '\t') {
        buf.deleteCharAt(len - 1);
      }
    }
    return buf.length() == 0 ? "" : buf.toString();
  }

  public static String format(String message, KeyValue... kvs) {
    return format(0, message, kvs);
  }

  public static String format(ResultData result, KeyValue... kvs) {
    return format(result.getCode(), result.getMessage(), kvs);
  }

  public static KeyValue kv(String key, Object value) {
    return new KeyValue(key, value);
  }

  public static LogHelper get() {
    return local.get();
  }

  public static void remove() {
    local.remove();
  }

  public String getIp() {
    return ip;
  }

  public void setIp(String ip) {
    this.ip = ip;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }


}

